package com.shf.config;

import com.alibaba.fastjson.JSONObject;

import com.shf.constants.URLConstants;
import com.shf.enums.TextCensorResultEnum;
import com.shf.util.AuthUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "baiduyun")
public class ContentCensor {

    private String clientId;
    private String clientSecret;

    /**
     * 文本审核
     *
     * @param text 待审核文本
     * @return 审核结果 { log_id, conclusion, conclusionType }
     * @throws Exception 审核异常
     */
    public Map<String, Object> textCensor(String text) throws Exception {

        String accessToken = AuthUtil.getAccessToken(clientId, clientSecret);
        FormBody formBody = new FormBody.Builder().add("text", text).build();
        Request request = new Request.Builder()
                .url(String.format(URLConstants.BAIDU_TEXT_CENSOR, accessToken))
                .method("POST", formBody)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();

        Response response = AuthUtil.HTTP_CLIENT.newCall(request).execute();
        String strBody = response.body().string();
        if (response.code() != HttpStatus.OK.value()) {
            JSONObject errObj = JSONObject.parseObject(strBody);
            log.error("百度文本审核接口调用失败：error_code: {}, error_msg: {}", errObj.getString("error_code"), errObj.getString("error_msg"));
            throw new RuntimeException("百度文本审核接口调用失败");
        }

        JSONObject resultObj = JSONObject.parseObject(strBody);
        Map<String, Object> result = new HashMap<>();
        result.put("log_id", resultObj.getString("log_id"));
        result.put("conclusion", resultObj.getString("conclusion"));
        result.put("conclusionType", resultObj.getShortValue("conclusionType"));
        return result;
    }

    /**
     * 图像审核
     *
     * @param imgParams 待审核图像列表 Base64字符串列表
     * @return 审核结果 { log_id, conclusion, conclusionType }
     * @throws Exception 审核异常
     */
    public Map<String, Object> imgCensor(List<String> imgParams) throws Exception {

        String accessToken = AuthUtil.getAccessToken(clientId, clientSecret);
        Request.Builder builder = new Request.Builder()
                .url(String.format(URLConstants.BAIDU_IMG_CENSOR, accessToken))
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json");

        Map<String, Object> result = new HashMap<>();
        for (String imgParam : imgParams) {
            FormBody formBody = new FormBody.Builder().add("image", imgParam).build();
            Request request = builder.method("POST", formBody).build();
            Response response = AuthUtil.HTTP_CLIENT.newCall(request).execute();
            String strBody = response.body().string();
            if (response.code() != HttpStatus.OK.value()) {
                JSONObject errObj = JSONObject.parseObject(strBody);
                log.error("百度图像审核接口调用失败：error_code: {}, error_msg: {}", errObj.getString("error_code"), errObj.getString("error_msg"));
                throw new RuntimeException("百度文本审核接口调用失败");
            }
            JSONObject resultObj = JSONObject.parseObject(strBody);
            Short conclusionType = resultObj.getShort("conclusionType");
            // 审核不是通过
            if (!Objects.equals(conclusionType, TextCensorResultEnum.COMPLIANCE.type())) {
                result.put("log_id", resultObj.getString("log_id"));
                result.put("conclusion", resultObj.getString("conclusion"));
                result.put("conclusionType", resultObj.getShortValue("conclusionType"));
                return result;
            }
        }
        result.put("conclusionType", TextCensorResultEnum.COMPLIANCE.type());
        return result;
    }
}
